package cn.edu.jssvc.litai.phonetest238;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int READ_PHONE_STATE_PERMISSION_REQUEST_CODE = 1;
    private Button startServiceBtn;
    private Button stopServiceBtn;

    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        intent=new Intent(this,MyService.class);
    }

    private void initView() {
        startServiceBtn = (Button) findViewById(R.id.start_service_btn);
        stopServiceBtn = (Button) findViewById(R.id.stop_service_btn);

        startServiceBtn.setOnClickListener(this);
        stopServiceBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {//活动开关按钮，主要功能在myservice活动里
        switch (v.getId()) {
            case R.id.start_service_btn:
                isGrantedPermission(this);
                startService(intent);
                Log.d("tag-btn","onClick:开启服务");
                break;
            case R.id.stop_service_btn:
                stopService(intent);
                Log.d("tag-btn","onClick:关闭服务");
                break;
        }
    }

    boolean isGrantedPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (activity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {//安卓9以上需要增加一个权限
                activity.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_CALL_LOG},
                        READ_PHONE_STATE_PERMISSION_REQUEST_CODE);
                return false;
            }
        } else {
            return true;
        }
        return true;
    }
}